package com.soyorin.user.controller;
import cn.hutool.http.HttpUtil;
import com.soyorin.user.entity.User;
import com.soyorin.user.service.UserService;
import org.springframework.http.ResponseEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService baseService;

    // 标准接口一: select-one
    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<User> selectById(@PathVariable Long id) {
        User User = baseService.getById(id);
        if(User != null) { // return1: 成功查询到数据
            return ResponseEntity.status(200).body(User);
        } else { // return2: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }

    // 标准接口二: select-all
    @GetMapping
    @ResponseBody
    public PageInfo<User> selectAll(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = baseService.list();
        return new PageInfo<>(list);
    }

    // 标准接口三: insert (增强版本，添加重复性检查)
    @PostMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> insert(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查账号是否已存在
            if (user.getAccount() != null && !user.getAccount().trim().isEmpty()) {
                QueryWrapper<User> accountWrapper = new QueryWrapper<>();
                accountWrapper.eq("account", user.getAccount());
                if (baseService.count(accountWrapper) > 0) {
                    response.put("success", false);
                    response.put("message", "账号已存在");
                    response.put("code", "ACCOUNT_EXISTS");
                    return ResponseEntity.status(400).body(response);
                }
            }
            
            // 检查邮箱是否已存在
            if (user.getBindEmail() != null && !user.getBindEmail().trim().isEmpty()) {
                QueryWrapper<User> emailWrapper = new QueryWrapper<>();
                emailWrapper.eq("bind_email", user.getBindEmail());
                if (baseService.count(emailWrapper) > 0) {
                    response.put("success", false);
                    response.put("message", "邮箱已被注册");
                    response.put("code", "EMAIL_EXISTS");
                    return ResponseEntity.status(400).body(response);
                }
            }
            
            // 检查手机号是否已存在
            if (user.getBindPhone() != null && !user.getBindPhone().trim().isEmpty()) {
                QueryWrapper<User> phoneWrapper = new QueryWrapper<>();
                phoneWrapper.eq("bind_phone", user.getBindPhone());
                if (baseService.count(phoneWrapper) > 0) {
                    response.put("success", false);
                    response.put("message", "手机号已被注册");
                    response.put("code", "PHONE_EXISTS");
                    return ResponseEntity.status(400).body(response);
                }
            }
            
            // 检查用户名是否已存在
            if (user.getName() != null && !user.getName().trim().isEmpty()) {
                QueryWrapper<User> nameWrapper = new QueryWrapper<>();
                nameWrapper.eq("name", user.getName());
                if (baseService.count(nameWrapper) > 0) {
                    response.put("success", false);
                    response.put("message", "用户名已存在");
                    response.put("code", "NAME_EXISTS");
                    return ResponseEntity.status(400).body(response);
                }
            }
            
            // 执行保存操作
            boolean result = baseService.save(user);
            if(result) { // return1: 成功插入数据
                response.put("success", true);
                response.put("message", "注册成功");
                response.put("data", user);
                return ResponseEntity.status(200).body(response);
            } else { // return2: 插入数据失败
                response.put("success", false);
                response.put("message", "注册失败，请稍后重试");
                response.put("code", "SAVE_FAILED");
                return ResponseEntity.status(500).body(response);
            }
            
        } catch (Exception e) {
            // 处理其他异常
            response.put("success", false);
            response.put("message", "注册失败：" + e.getMessage());
            response.put("code", "SYSTEM_ERROR");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 标准接口四: delete
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResponseEntity<User> delete(@PathVariable Long id) {
        User User = baseService.getById(id);
        if(User != null) {
            boolean result = baseService.removeById(id);
            if(result) { // return1: 成功删除数据
                return ResponseEntity.status(200).body(User);
            } else { // return2: 删除数据失败
                return ResponseEntity.status(500).body(User);
            }
        } else { // return3: 未找到对应数据
            return ResponseEntity.status(404).body(null);
        }
    }

    // 标准接口五: update
    @PutMapping("/{id}")
    @ResponseBody
    public ResponseEntity<User> update(
            @PathVariable Long id,
            @RequestBody User User) {
        User.setId(id);
        boolean result = baseService.updateById(User);
        User updateUser = baseService.getById(User.getId());
        if(result && updateUser != null) { // return1: 成功更新数据
            return ResponseEntity.status(200).body(updateUser);
        } else { // return2: 更新数据失败
            return ResponseEntity.status(500).body(User);
        }
    }

    // 标准接口六: select-eq
    @PostMapping("/select-eq")
    @ResponseBody
    public ResponseEntity<List<User>> selectEq(
            @RequestBody Map<String,Object> conditions) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        for(Map.Entry<String, Object> entry : conditions.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            wrapper.eq(key, value);
        }
        List<User> list = baseService.list(wrapper);
        if(!list.isEmpty()) { // return1: 成功查询到数据
            return ResponseEntity.status(200).body(list);
        } else { // return2: 未找到对应数据
            return ResponseEntity.status(404).body(Collections.emptyList());
        }
    }

    // 查看店铺
    @GetMapping("/user-goods")
    @ResponseBody
    public String userShop(@RequestParam Long userId) {
        User User = baseService.getById(userId);
        String result = HttpUtil.get("http://localhost:9001/goods/" + userId);
        Long userId1 = userId + 2L;
        User User1 = baseService.getById(userId1);
        String result1 = HttpUtil.get("http://localhost:9001/goods/" + userId1);
        Long userId2 = userId1 + 2L;
        User User2 = baseService.getById(userId2);
        String result2 = HttpUtil.get("http://localhost:9001/goods/" + userId2);
        Long userId3 = userId2 + 2L;
        User User3 = baseService.getById(userId3);
        String result3 = HttpUtil.get("http://localhost:9001/goods/" + userId3);
        return User + result + result1 + result2 + result3;
    }

    
    // 新增接口：检查字段唯一性
    @PostMapping("/check-unique")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> checkUnique(@RequestBody Map<String, String> checkData) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String field = checkData.get("field");
            String value = checkData.get("value");
            
            if (field == null || value == null || value.trim().isEmpty()) {
                response.put("available", false);
                response.put("message", "参数不能为空");
                return ResponseEntity.status(400).body(response);
            }
            
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq(field, value);
            long count = baseService.count(wrapper);
            
            response.put("available", count == 0);
            response.put("message", count == 0 ? "可以使用" : "已被使用");
            return ResponseEntity.status(200).body(response);
            
        } catch (Exception e) {
            response.put("available", false);
            response.put("message", "检查失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}